package com.qf.hotel.factory;

import java.io.*;
import java.util.Properties;

/**
 * 生成对象的工厂类
 *
 * foodTypeService=com.qf.hotel.service.impl.FoodTypeServiceImpl
 */
public class BeanFactory {
    private static final Properties PROPERTIES = new Properties();

    static {
        InputStream is = null;
        try {
            is = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            PROPERTIES.load(is);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 通过对象名获取对象的方式
     * @param beanName
     * foodTypeService=com.qf.hotel.service.impl.FoodTypeServiceImpl
     * beanName===》foodTypeService
     * 通过beanName获取类名
     * 通过类名创建对象
     * @return
     * @throws ClassNotFoundException
     */
    public static Object getBean(String beanName){
        Object instance = null;
        try {
            // 1、获取类名
            String className = PROPERTIES.getProperty(beanName);
            Class<?> clazz = Class.forName(className);

            // 2、创建对象
            instance = clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return instance;
    }
}
